package com.example.tests;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

import java.util.Random;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import com.example.obj.ContactObject;
import com.example.obj.ContactSet;
import com.example.obj.GroupSet;

public class Test_03_ContactCreation extends TestBase{
	
	@Test(priority = 2, dataProvider = "contactsFromFile", dataProviderClass = ContactDataGenerator.class)
	public void testContactCanBeCreated(ContactObject validContact, boolean valid) throws Exception {
		log.info("Start testContactCanBeCreated");
		GroupSet groups = manager.getGroupHelper().getGroupsCouche();
		if (groups.size() != 0) {
			Random rnd = new Random();
			validContact.setGroupName(groups.getElement(rnd.nextInt(groups.size())).name);
		}
		ContactSet oldContactSet = manager.getContactHelper().getContactsCache();
		log.info("Old contacts list: " + oldContactSet);
		manager.getContactHelper().createContact(validContact);
		ContactSet newContactSet = manager.getContactHelper().getContactsCache();
		log.info("New contacts list: " + newContactSet);
		log.info("Start assertions: size, lists' elements");
		if (valid){
			assertThat(newContactSet.size(), equalTo(oldContactSet.size() + 1));
			assertThat(newContactSet, equalTo(oldContactSet.with(validContact)));
		}
		else{
			assertThat(newContactSet.size(), equalTo(oldContactSet.size()));
			assertThat(newContactSet, equalTo(oldContactSet));			
		}
		log.info("Stop assertions");
	}
	
	@AfterMethod
	public void testUIConfirmWithDB(){
		log.info("After testContactCanBeCreated");
		ContactSet contactsUI = manager.getContactHelper().getContactsUI();
		log.info("Contacts from UI: " + contactsUI);		
		ContactSet contactsDB = manager.getContactHelper().getCacheCopy();
		log.info("Contacts from DB: " + contactsDB);
		assertThat(contactsDB, equalTo(contactsUI));
	}
}
